package name.luoyong.spring.sample.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import javax.validation.Valid;

import name.luoyong.spring.sample.dao.UserDao;
import name.luoyong.spring.sample.entity.User;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
	
	private static final String StrCurrentUser = "currentUser";
	
	@Autowired
	private UserDao userDao;
	
	public UserService() {
		System.out.println("****** UserService init *******");
	}
	
	@Transactional
	public void add(User user) {
		userDao.save(user);
	}
	
	public User getCurrentUser(HttpSession session) {
		User user = (User)session.getAttribute(StrCurrentUser);
		if(user == null) {
			Subject subject = SecurityUtils.getSubject();
			
			if( !subject.isAuthenticated() && !subject.isRemembered()) {
				return null;
			}
			
			String username = (String) subject.getPrincipal();
			user = getUserByUsername(username);
			session.setAttribute(StrCurrentUser, user);
		}
		return user;
	}
	
	public User getCurrentUser(HttpServletRequest request) {
		return getCurrentUser(request.getSession());
	}
	
	@Transactional
	public User get(Long id) {
		return userDao.get(id);
	}
	
	@Transactional
	public void update(User user) {
		userDao.update(user);
	}
	
	@Transactional
	public void delete(User user) {
		userDao.delete(user);
	}
	
	@Transactional
	public int delete(Long id) {
		return userDao.delete(id);
	}
	
	@Transactional
	public User getUserByUsername(String username) {
		return userDao.getUserByUsername(username);
	}
	
	@Transactional
	public List<User> getAllUser() {
		return userDao.getAllUsers();
	}

	public boolean isExistByUsername(String username) {
		int count = userDao.countByUsername(username);
		if(count == 0) {
			return false;
		} else {
			return true;
		}
	}

}
